package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojp.TUser;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 28463
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-06-16 13:50:02
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{
    @Autowired
    TUserMapper tUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R sendCode(String mobile) {
        //60秒只能发送一次验证码
        String sendKey="send-"+mobile;
        Boolean hasKey = stringRedisTemplate.hasKey(sendKey);
        if(hasKey){
            return R.ERROR(500,"验证码发送频繁");
        }
        stringRedisTemplate.opsForValue().set(sendKey,"1",60, TimeUnit.SECONDS);


        //校验手机号格式
        boolean mobile1 = Validator.isMobile(mobile);
        if(!mobile1){
            return R.ERROR(500,"手机号格式不正确");
        }

        TUser tUser = tUserMapper.selectOne(new QueryWrapper<TUser>().lambda().eq(TUser::getMobile, mobile));
        if(tUser==null){
            return R.ERROR(500,"手机号不存在");
        }
        //发送验证码
        String mobileCode = RandomUtil.randomNumbers(4);
        MobileMessageUtil.sendMobileMessage(mobile,mobileCode);
        String mobileKey="mobileCode-"+mobile;
        stringRedisTemplate.opsForValue().set(mobileKey,mobileCode,1,TimeUnit.MINUTES);
        System.out.println("手机号验证码为:"+mobileCode);
        return R.OK(mobileCode);
    }
}




